/**
 * 
 */
package io.potato.core.web;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import io.potato.core.BaseEntity;
import io.potato.core.util.JsonUtils;

import java.util.Iterator;

/**
 * Entity 参数解析
 * @author timl
 * created: 2018年11月5日 上午10:55:36
 */
public class EntityResolver implements HandlerMethodArgumentResolver {
	@Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (parameter.getParameterType().getSuperclass().equals(BaseEntity.class)) {
            return true;
        }
        return false;
    }
 
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    	
    	JSONObject jsonObject = new JSONObject();
    	Iterator<String> paramNames = webRequest.getParameterNames();
    	while (paramNames.hasNext()) {
			String paramName = paramNames.next();
			String paramValue = webRequest.getParameter(paramName);
			if (StringUtils.isNotEmpty(paramValue)) {
				jsonObject.put(paramName, paramValue);
			}
		}

        return JsonUtils.decode(jsonObject.toString(), parameter.getParameterType());
    }
}
